﻿using Dapper;
using System.Collections;
using Volo.Abp.DependencyInjection;
using YAKEJI.Abp.Database;
using YAPACS.Workflows;

namespace YAPACS.RisServer.Workflows.SyncData;

public class GetExamItem : WorkflowBase, IGetExamItem, ITransientDependency
{
    private readonly IDatabaseConnectionProvider _connectionProvider;

    public GetExamItem(IDatabaseConnectionProvider connectionProvider)
    {
        _connectionProvider = connectionProvider;
    }

    protected override async Task<WorkflowOutput> InvokeCoreAsync(WorkflowInput input)
    {
        return new WorkflowOutput { Success = true };
        const string departmentCodeKey = "DepartmentCode", deviceTypeCodeKey = "DeviceTypeCode";
        if (input.ContainsKey(departmentCodeKey) && input.ContainsKey(deviceTypeCodeKey))
        {
            var _departmentCode = input.GetValueOrDefault(departmentCodeKey) as string;
            var _deviceTypeCode = input.GetValueOrDefault(deviceTypeCodeKey) as string;
            var departmentCode = GetDepartmentCode(_departmentCode);
            var deviceTypeCode = GetDeviceCode(_deviceTypeCode);
            if (string.IsNullOrWhiteSpace(departmentCode)) throw new Exception("未找到科室对应编码");
            if (string.IsNullOrWhiteSpace(deviceTypeCode)) throw new Exception("未找到设备类型对应编码");
            var list = await GetListByDatabaseAsync(departmentCode, deviceTypeCode);
            return new WorkflowOutput
            {
                Success = true,
                Data = list
            };
        }
        return new WorkflowOutput
        {
            Success = false,
            Error = "未找到参数"
        };
    }
    private async Task<object> GetListByDataSourceAsync(string departmentCode, string deviceTypeCode)
    {
        string path = @"D:\yapacs\data\datasource";
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }
        string filePath = Path.Combine(path, @"ExamItem.json");
        if (!File.Exists(filePath))
        {
            throw new Exception("数据文件不存在");
        }
        var context = await File.ReadAllTextAsync(filePath);
        var dic = context.Deserialize<Dictionary<string, List<Result.ExamItemDto>>>();
        var list = dic.GetValueOrDefault(deviceTypeCode.ToUpper());
        return list ?? [];
    }
    /// <summary>
    /// 数据库方式获取
    /// </summary>
    /// <param name="departmentCode"></param>
    /// <param name="deviceTypeCode"></param>
    /// <returns></returns>
    private async Task<IEnumerable> GetListByDatabaseAsync(string departmentCode, string deviceTypeCode)
    {
        //const string connectionString = @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=HIS;Integrated Security=True;Connect Timeout=30;Encrypt=False;Trust Server Certificate=False;Application Intent=ReadWrite;Multi Subnet Failover=False";
        const string connectionString = @"Server=192.168.2.82;Initial Catalog=HIS;User Id=sa;Password=pacs@1234;TrustServerCertificate=True";
        using var connection = _connectionProvider.GetDbConnection(connectionString, DatabaseType.SqlServer);
        string condition = " where DepartmentCode=@DepartmentCode and DeviceTypeCode=@DeviceTypeCode";
        string sql = @"select Name,Code,Fee,Parent from pacs_view_exam_item" + condition;
        var list = await connection.QueryAsync(sql, new { DepartmentCode = departmentCode, DeviceTypeCode = deviceTypeCode });
        return list;
    }
    /// <summary>
    /// Get方式获取
    /// </summary>
    /// <param name="departmentCode"></param>
    /// <param name="deviceTypeCode"></param>
    /// <returns></returns>
    private async Task<IEnumerable> GetListByGetWebapiAsync(string departmentCode, string deviceTypeCode)
    {
        //组装参数
        string url = "";
        //线上工作流，需要把接口调用这段代码写完整
        var result = await Extensions.GetAsync<Result>(url);
        //处理接口返回的数据
        if (result.Code == 200)
        {
            var list = result.Data.Select(e => new
            {
                e.Code,
                e.Name,
                e.Fee,
                e.Parent
            });
            return list;
        }
        else
        {
            throw new Exception(result.Message);
        }
    }
    /// <summary>
    /// Post方式获取
    /// </summary>
    /// <param name="departmentCode"></param>
    /// <param name="deviceTypeCode"></param>
    /// <returns></returns>
    private async Task<IEnumerable> GetListByPostWebapiAsync(string departmentCode, string deviceTypeCode)
    {
        //组装参数
        string url = "";
        var result = await Extensions.PostAsync<object, Result>(url, new { DepartmentCode = departmentCode, DeviceTypeCode = deviceTypeCode });
        if (result.Code == 200)
        {
            var list = result.Data.Select(e => new
            {
                e.Code,
                e.Name,
                e.Fee,
                e.Parent
            });
            return list;
        }
        else
        {
            throw new Exception(result.Message);
        }
    }

    private string GetDepartmentCode(string code)
    {
        return code.ToUpper() switch
        {
            _ => code
        };
    }

    private string GetDeviceCode(string code)
    {
        return code switch
        {
            _ => code
        };
    }


    /// <summary>
    /// 接口或者数据库映射的类，按照实际项目修改属性名称
    /// </summary>
    public class Result
    {
        public int Code { get; set; }
        public string Message { get; set; }
        public IList<ExamItemDto> Data { get; set; }

        public class ExamItemDto
        {
            public string Code { get; set; }
            public string Name { get; set; }
            public decimal Fee { get; set; }
            public string Parent { get; set; }
        }
    }
}
